#include <ESP8266WiFi.h>
#include <WiFiUdp.h>
#include "DHT.h"
#include <MySQL_Connection.h>    // Arduino连接Mysql的库
#include <MySQL_Cursor.h>
#include <Wire.h> //IIC
#include <math.h> 

 
#define SDA_PIN 4
#define SCL_PIN 5
#define DHTPIN 2  
#define DHTTYPE DHT11
#define FAN 15
#define LIGHT 1
#define key1  13
#define key2  14
#define key3  12
DHT dht(DHTPIN, DHTTYPE);

void get_mode(void);
void light_mode(void);
void fan_mode(void);
float sortdata1(float p[30]);
void FAN_control(float humidity);
void Light_concrol(int light);
int BH1750_Read(int address); 
void BH1750_Init(int address) ;
void humidity_get(void);

const char* ssid = "221";     //"221"; 
const char* password = "796380221";    //"796380221";

int flag1 = 0;
int flag2 = 0;
int flag3 = 0;

unsigned int localUdpPort = 8266;  // 本地监听端口
unsigned int remote_Port = 8666;

WiFiUDP Udp;
IPAddress remote_IP(192, 168, 3, 83);
IPAddress local_IP(192, 168, 3, 166);
IPAddress gateway(192, 168, 3, 9);
IPAddress subnet(255, 255, 255, 0);

char sql_user[] = "root";              // Mysql的用户名
char sql_password[] = "lqh270774337";        // 登陆Mysql的密码
char INSERT_SQL[] = "INSERT INTO  mysql.humidity_temperature(tem,hem) VALUES ('%s','%s')";

float h;
float t; 
int light=0;
float temperature_data[30]={0};
float humidity_data[30]={0};
char data_send[255];
String data_handle="";
int run_mode = 1;
int light_status = 0;
int fan_status = 0;

int BH1750address = 0x23; 
byte buff[2];

WiFiClient client;                 // 声明一个Mysql客户端，在lianjieMysql中使用
MySQL_Connection conn(&client);
MySQL_Cursor* cursor;    // 

void setup()
{
  pinMode(BUILTIN_LED, OUTPUT);     // Initialize the BUILTIN_LED pin as an output
  Serial.begin(115200);
  pinMode(FAN,OUTPUT);
  pinMode(LIGHT,OUTPUT);
  GPIO_DIS_OUTPUT(key1);
  GPIO_DIS_OUTPUT(key2);
  GPIO_DIS_OUTPUT(key3);
  Wire.begin(SDA_PIN, SCL_PIN);

 // Wire.onReceive(receiveEvent); 
  Serial.println();
  WiFi.config(local_IP, gateway, subnet);
  Serial.printf("Connecting to %s",ssid);
  WiFi.begin(ssid,password);
  while (WiFi.status() != WL_CONNECTED)
  {
    delay(500);
    Serial.print(".");
  }
  Serial.println(" connected");
  Serial.printf("begin Udp");
  Serial.printf("Now listening at IP %s, UDP port %d\n", WiFi.localIP().toString().c_str(), localUdpPort);
  Udp.begin(localUdpPort);
  /*
  while (!conn.connect(remote_IP, 3306, sql_user, sql_password))         // 连接数据库
  {
      Serial.println(".");   
      delay(500);
  }  
  Serial.println("OK.");
  cursor = new MySQL_Cursor(&conn);    // 创建一个数据库游标实例
  */
}

 

void loop()

{
  get_mode();  
  if(run_mode){
    light_mode();
    fan_mode();
    if(light_status==0)
        digitalWrite(LIGHT,LOW);
    else
        digitalWrite(LIGHT,HIGH);
    if(fan_status==0)
        digitalWrite(FAN,LOW);
    else
        digitalWrite(FAN,HIGH); 
    humidity_get();
  }
  else{
   humidity_get();
  delay(1000);
  FAN_control(h);
  Light_concrol(light);
  //Serial.println("LIGHT:");
  //Serial.println(digitalRead(2));
  }
  data_handle+=h;
  data_handle+="|";
  data_handle+=t;
  data_handle+="|";
  data_handle+=light;  
  data_handle.toCharArray(data_send,data_handle.length()+1);
  Udp.beginPacket(remote_IP, remote_Port);
  Udp.write(data_send);
  Udp.endPacket();
  data_handle="";
}


float sortdata1(float p[30]){
    int j, k;
    float temp;
    for(j=0; j<30-1; j++){
        for(k=0; k<30-1-j; k++){
            if(p[k] > p[k+1]){
                temp = p[k];
                p[k] = p[k+1];
                p[k+1] = temp;
            }
        }
    }
  return p[5];
}

void FAN_control(float humidity)
{
  if(humidity >=40.0 && humidity <= 65.0)
  digitalWrite(FAN,LOW);
  else{
    digitalWrite(FAN,HIGH);
    Serial.println("FAN begin");
  }
  
}

void Light_concrol(int light)
{
  if(light<300)
  digitalWrite(LIGHT,HIGH);
  else
  digitalWrite(LIGHT,LOW);
}

int BH1750_Read(int address) //

{

  int i=0;

  Wire.beginTransmission(address);

  Wire.requestFrom(address, 2);

  while(Wire.available()) //

  {

    buff[i] = Wire.read();  // receive one byte

    i++;

  }

  Wire.endTransmission();  

  return i;

}




void BH1750_Init(int address) 

{

  Wire.beginTransmission(address);

  Wire.write(0x10);//1lx reolution 120ms

  Wire.endTransmission();

}


void get_mode(void){
  if(digitalRead(key1)==HIGH)
  flag1 = 1;
  if(digitalRead(key1)==LOW && flag1 == 1)
  {
   if(run_mode==1)run_mode=0;
   else run_mode=1;
   flag1 =0; 
  }
}

void fan_mode(void)
{
  if(digitalRead(key2)==HIGH)
  flag2 = 1;
  if(digitalRead(key2)==LOW && flag2 == 1)
  {
   if(fan_status==0)fan_status=1;
   else fan_status=0;
   flag2 =0; 
  }
}

void light_mode(void)
{
  if(digitalRead(key3)==HIGH)
  flag3 = 1;
  if(digitalRead(key3)==LOW && flag3 == 1)
  {
   if(light_status==0)light_status=1;
   else light_status=0;
   flag3 =0; 
  }
}

void humidity_get(void)
{
  int i;
  uint16_t val=0;
  BH1750_Init(BH1750address);
  delay(200);
 if(2==BH1750_Read(BH1750address))
  {
   val=((buff[0]<<8)|buff[1])/1.2;
   Serial.println("light begin");
   Serial.print(val,DEC);     
   light = val;
   Serial.println("[lx]"); 
  }
 delay(150);
  for(int i=0;i<30;i++)
  {
    while(isnan(dht.readHumidity()) || isnan(dht.readTemperature())) {
    Serial.println("Failed to read from DHT sensor!");
    delay(500);
    }
    humidity_data[i]=dht.readHumidity();;
    temperature_data[i]=dht.readTemperature(); 
    h = sortdata1(humidity_data) ;
    t = sortdata1(temperature_data);  
  }
}
